# -*- coding:utf-8 -*-

"""
    上传包之前，先校验此包是否存在
"""

import tornado.web
from service import base
from utils.routes import route
from utils import log as logger
from utils import mongo
from configure import config


@route('/file/check_exits/?', 'file.check_exits')
class CheckFileExistsHandler(base.BaseWebHandler):
    """ 校验此包是否存在
    """
    db_name = config.DB_NAME
    collection_name = config.COLLECTION_DATAS


    @tornado.web.asynchronous
    @tornado.gen.engine
    def get(self, *argl, **argd):
        md5 = self.get_argument('md5', None)
        filename = self.get_argument('filename', None)
        logger.info('filename:', filename, 'md5:', md5, caller=self)

        if not md5 or not filename:
            self.finish({'code': 1, 'info': 'params error!'})
            return

        l = filename[:-4].split('_')
        if len(l) != 4 or '' in l:
            self.finish({'code': 2, 'info': 'filename error!'})
            return
        sn_ids_str, ver_from, ver, create_time = l[0], l[1], l[2], l[3]

        spec = {
            '$or': [
                {'md5': md5},
                {'filename': filename},
                {'sn_ids_str': sn_ids_str, 'ver_from': ver_from, 'ver': ver}
            ]
        }
        d = yield tornado.gen.Task(mongo.find_one, config.DB_NAME, config.COLLECTION_DATAS, spec)
        if d:
            self.finish({'code': 3, 'info': 'file exists!'})
            return

        self.finish({'code': 0, 'info': 'ok.'})
